import GameInfo from './runtime/gameinfo'
import Music from './runtime/music'
import Scene from './scenes/index'
import util from './base/util'
import Render from './render/index'
import rea from './base/rea'
//import Test from './interface/interface'

export default class Main {
  constructor() {    
    rea.pipelines().find("socketStatusChanged").nextF(aInput => {
      if (aInput.data())
        this.online()
    })

    util.login().then(res => {
      util.request({
        api: "astray/openid",
        data: {code: res.code}}).then(res => {
          if (res && res.data != "Not Found"){
            this.openid = res.data.openid
          }else{
            this.openid = "robbeykaaso"
            //return
          }
          rea.pipelines().run("socketStatusChanged", false)
            // 维护当前requestAnimationFrame的id
            this.aniId = 0
            this.render = new Render.rWebgl()
            this.scenes = {start: new Scene.Starting(this, this.openid, "start"), 
                          //train: new Scene.Swinging(this),
                          //train: new Scene.Training(this),
                          train: new Scene.Astray(this, this.openid, "train"),
                          remote: new Scene.AstrayRemote(this, this.openid, "remote"),
                          //loading: new Scene.Loading(this)
                          loading: new Scene.AstraySingle(this, this.openid, "loading"),
                          loading2: new Scene.AstrayMulti(this, this.openid, "loading2"),
                          shop: new Scene.AstrayShop(this, this.openid, "shop")
                          }
            this.gameinfo = new GameInfo()
            this.music = new Music()
            this.bindLoop = this.loop.bind(this)
            this.switchScene("start")
          
        })
      })
  }

  online(){
    util.request2({type: "who", id: this.openid})
  }

  async switchScene(aScene, aParam){
    if (this.current_scene){
      window.cancelAnimationFrame(this.aniId)
      this.scenes[this.current_scene].leave()
    }
    let prm = aParam || {}
    prm.lastScene = this.current_scene
    await this.scenes[aScene].enter(prm)
    this.current_scene = aScene
    this.nextloop()
  }

  nextloop(){
    this.aniId = window.requestAnimationFrame(
      this.bindLoop,
      canvas
    )
  }

  async loop() {
    const sc = this.scenes[this.current_scene]
    let ret = sc.update()
    if (ret.scene && ret.scene != ""){
      await this.switchScene(ret.scene, ret.param)
    }else{
      await sc.render(this.render)
      this.nextloop()
    }
  }
}
